package com.xd.core.business.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.common.util.AESUtil;
import com.xd.common.util.SecurityUtil;
import com.xd.core.business.dto.CertificationDto;
import com.xd.core.business.dto.CertificationQuery;
import com.xd.core.business.entity.Certification;
import com.xd.core.business.entity.Contract;
import com.xd.core.business.entity.IncomingInfo;
import com.xd.core.business.entity.OutInfo;
import com.xd.core.business.mapper.ContractMapper;
import com.xd.core.business.mapper.IncomingInfoMapper;
import com.xd.core.business.mapper.OutInfoMapper;
import com.xd.core.business.service.ICertificationService;
import com.xd.core.business.vo.CertificationDetailVo;
import com.xd.core.business.vo.CertificationPageVo;
import com.xd.core.business.vo.CertificationVo;
import com.xd.core.debt.entity.Debt;
import com.xd.core.debt.mapper.DebtMapper;
import com.xd.core.mission.entity.MissionCenterInfo;
import com.xd.core.mission.mapper.MissionCenterInfoMapper;
import com.xd.core.system.entity.CityInfo;
import com.xd.core.system.mapper.CityInfoMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 公证表 前端控制器
 * </p>
 *
 * @author ZX
 * @since 2025-02-27
 */
@Api(tags = "公证")
@RestController
@RequestMapping("/business/certification")
public class CertificationController {
    @Autowired
    private ICertificationService iCertificationService;
    @Autowired
    private IncomingInfoMapper incomingInfoMapper;
    @Autowired
    private MissionCenterInfoMapper missionCenterInfoMapper;
    @Autowired
    private CityInfoMapper cityInfoMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private DebtMapper debtMapper;
    @Autowired
    private OutInfoMapper outInfoMapper;

    @PreAuthorize("hasAnyAuthority('sys:Incoming-InitiateNotarization')")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("按钮--办理公证")
    @GetMapping("/insertCertification/{incomingId}/{outId}")
    public void insertCertification(@PathVariable Integer incomingId,@PathVariable Integer outId) {
        IncomingInfo incomingInfo = incomingInfoMapper.selectById(incomingId);
        if (SysConstant.ORDER_DISABLE.equals(incomingInfo.getIsEnable())) {
            throw new XkdException("该订单已被平台停用");
        }
        Integer count = contractMapper.selectCount(new LambdaQueryWrapper<Contract>()
                .eq(Contract::getOutId, outId).in(Contract::getType, SysConstant.CONTRACT_TYPE_SIX,SysConstant.CONTRACT_TYPE_SEVEN)
                .eq(Contract::getStatus,SysConstant.CONTRACT_DO));
        if (count != 2) {
            throw new XkdException("用户有合同未签署完毕");
        }
        Certification certification = new Certification();
        certification.setIncomingId(incomingId);
        certification.setStatus("0");
        certification.setOutId(outId);
        iCertificationService.save(certification);
        outInfoMapper.updateStatus(SysConstant.BUSINESS_STATUS_TEN, outId);
    }

    @ApiOperation("按钮--重新公证")
    @GetMapping("/reTryCertification/{incomingId}/{outId}")
    public void reTryCertification(@PathVariable Integer incomingId,@PathVariable Integer outId) {
        IncomingInfo incomingInfo = incomingInfoMapper.selectById(incomingId);
        if (SysConstant.ORDER_DISABLE.equals(incomingInfo.getIsEnable())) {
            throw new XkdException("该订单已被平台停用");
        }
        Integer count = contractMapper.selectCount(new LambdaQueryWrapper<Contract>()
                .eq(Contract::getOutId, outId)
                .in(Contract::getType, SysConstant.CONTRACT_TYPE_SIX,SysConstant.CONTRACT_TYPE_SEVEN)
                .eq(Contract::getStatus,SysConstant.CONTRACT_DO));
        if (count != 2) {
            throw new XkdException("用户有合同未签署完毕");
        }
        UpdateWrapper<Certification> eq = Wrappers.<Certification>update().set("status", "0").eq("out_id", outId);
        iCertificationService.update(eq);
    }

    @PreAuthorize("hasAnyAuthority('sys:NotarizedOrder-viewDetails','sys:NotarizedOrder')")
    @ApiOperation("公证列表")
    @PostMapping("/getCertification")
    public Page<CertificationPageVo> getList(@RequestBody CertificationQuery query) {
        return iCertificationService.getList(query);
    }

    @ApiOperation("公证详情")
    @GetMapping("/getCfnDetail/{id}")
    public CertificationDetailVo getCertification(@PathVariable Integer id) {
        return iCertificationService.getCertification(id);
    }


    @ApiOperation("线下办理公证详情")
    @GetMapping("/getOfflineCfnDetail/{id}")
    public CertificationDetailVo getOfflineCfnDetail(@PathVariable Integer id) {
        Certification certification = iCertificationService.getOne(new LambdaQueryWrapper<Certification>().eq(Certification::getOutId, id));
        if (!certification.getStatus().equals(SysConstant.CERTIFICATION_STATUS_ZERO)){
            throw new XkdException("订单正在公证中");
        }
        return iCertificationService.getCertification(id);
    }

    @ApiOperation("线下办理公证提交")
    @PostMapping("/getOfflineCfnDetail")
    public void getOfflineCfnDetail(@RequestBody CertificationDto certificationDto) {
        Integer incomingId = certificationDto.getIncomingId();
        Integer outId = certificationDto.getOutId();
        IncomingInfo incomingInfo = incomingInfoMapper.selectById(incomingId);
        if (SysConstant.ORDER_DISABLE.equals(incomingInfo.getIsEnable())) {
            throw new XkdException("该订单已被平台停用");
        }
        Certification certification = iCertificationService.getOne(new LambdaQueryWrapper<Certification>().eq(Certification::getOutId, outId));
        if (certification.getStatus().equals(SysConstant.CERTIFICATION_STATUS_TOW)){
            throw new XkdException("订单已完成公证，不允许修改");
        }
        if (certificationDto.getStatus().equals(SysConstant.CERTIFICATION_STATUS_TOW)){
            outInfoMapper.updateStatus(SysConstant.BUSINESS_STATUS_ELEVEN,outId);
        }else{
            outInfoMapper.updateStatus(SysConstant.BUSINESS_STATUS_TEN,outId);
        }
        iCertificationService.updateById(BeanUtil.copyProperties(certificationDto,Certification.class));
    }

    @ApiOperation("导出--公证列表")
    @PostMapping("/exportCertification")
    public void exportCustomerInfoList(@RequestBody CertificationQuery query) {
        //插入数据状态是正在导出
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setCompanyId(SecurityUtil.getLoginCompanyId());
        missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_ONE);
        missionCenterInfo.setCreateTime(new Date());
        missionCenterInfo.setUserId(SecurityUtil.getLoginUserId());
        missionCenterInfoMapper.insert(missionCenterInfo);

        iCertificationService.exportIncomingInfoList(query, missionCenterInfo.getId());
    }

    @ApiOperation("业务详情--公证信息")
    @GetMapping("/getCertificationDetail/{id}")
    public CertificationVo getCertificationDetail(@PathVariable Integer id) {
        CertificationVo certificationVo = new CertificationVo();
        Debt debt = debtMapper.selectOne(new LambdaQueryWrapper<Debt>().eq(Debt::getIncomingId, id));
        OutInfo outInfo = outInfoMapper.selectById(debt.getOutId());
        debt.setCertificationApplyStatus("未办理");
        if (ObjectUtil.isNotEmpty(debt)) {
            String status = debt.getCertificationApplyStatus();
            if ("1".equals(status)) {
                status = "办理申请中";
            } else if ("2".equals(status)) {
                status = "办理完成";
            }
            Date certificationApplyDate = debt.getCertificationApplyDate();
            certificationVo.setCertificationApplyDate(certificationApplyDate);
            certificationVo.setCertificationApplyStatus(status);
        }
//        IncomingInfo incomingInfo = incomingInfoMapper.selectById(id);
        String controversy = outInfo.getControversy();
        certificationVo.setControversy(outInfo.getControversy());
        if (SysConstant.CONTROVERSY_ONE.equals(controversy)) {
            return iCertificationService.getCertificationDetail(id);
        } else if (SysConstant.CONTROVERSY_TOW.equals(controversy)) {
            String citySqes = outInfo.getCitySqes();
            String substring = citySqes.substring(citySqes.lastIndexOf(',') + 1);
            CityInfo cityInfo = cityInfoMapper.select(substring);
            certificationVo.setProvince(cityInfo.getProvinceName());
            certificationVo.setCity(cityInfo.getExtName());
            return certificationVo;
        } else {
            return certificationVo;
        }
    }


}
